﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using Microsoft.Phone.Tasks;

namespace nyxwin.Common.Providers
{
    public class LinkHandler
    {
        private List<ILinkFilter> _filters;

        private LinkHandler()
        {
            _filters = new List<ILinkFilter>();
        }

        private static LinkHandler _instance = null;
        private static object _lock = new object();

        public static LinkHandler Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                            _instance = new LinkHandler();
                    }
                }

                return _instance;
            }
        }

        public Uri BaseUri { get; set; }

        private Uri CreateUri(string uri)
        {
            Uri prevUri = null;

            if (uri.StartsWith("?"))
                prevUri = new Uri(uri, UriKind.Relative);
            else
                prevUri = new Uri(uri);

            if (BaseUri != null)
                return new Uri(BaseUri, prevUri);
            else
                return prevUri;
        }

        public void OpenInBrowser(string uri)
        {
            var combinedUri = CreateUri(uri);
            OpenInBrowser(combinedUri);
        }

        public void FollowLink(string uri)
        {
            var combinedUri = CreateUri(uri);

            foreach (var filter in _filters)
            {
                if (filter.HandleLink(combinedUri, uri))
                    return;
            }

            OpenInBrowser(uri);
        }

        private void OpenInBrowser(Uri uri)
        {
            if (MessageBox.Show(uri.ToString(), "Open link?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                WebBrowserTask wbt = new WebBrowserTask();
                wbt.Uri = uri;
                wbt.Show();
            }
        }

        public void Register(ILinkFilter filter)
        {
            _filters.Add(filter);
        }

        public void UnRegister(ILinkFilter filter)
        {
            if (_filters.Contains(filter))
                _filters.Remove(filter);
        }

        public interface ILinkFilter
        {
            bool HandleLink(Uri combinedUri, string originalLink);
        }
    }
}
